import classNames from 'classnames';
import { useEffect, useState } from 'react';
import styles from './index.less';
interface CheckTagProps {
  data: { label: string; value: any }[];
  defaultValue?: any[];
  onChange?: (value: any[], originValue?: { label: string; value: any }[]) => void;
  type?: 'default' | 'green';
  controled?: boolean;
}
const CheckTag: React.FC<CheckTagProps> = ({
  data,
  defaultValue = [],
  onChange,
  type = 'default',
  controled = false,
}) => {
  const [value, setValue] = useState(defaultValue);
  useEffect(() => {
    if (controled) {
      setValue(defaultValue);
    }
  }, [defaultValue, controled]);
  const handleClick = (item) => {
    let newValue = [item.value];
    if (Array.isArray(item.value) && item.value.length > 1) {
      if (value[0] !== item.value[0]) {
        newValue = [item.value[0]];
      } else {
        newValue = [item.value[1]];
      }
    }
    setValue(newValue);

    onChange?.(newValue);
    // const index = value.findIndex(_item => _item === item.value);
    // if (index < 0) {
    //     const newValue = [...value, item.value];
    //     setValue(newValue)
    // }
  };

  const isActived = (item) => {
    if (!Array.isArray(item.value)) {
      return value.includes(item.value);
    }
    return item.value.some((obj) => value.includes(obj));
  };
  const iconIsActived = (item, index) => {
    return value.includes(item.value[index]);
  };

  return (
    <div className={classNames(styles.checkTag, styles[type], 'z-check-tag')}>
      {data.map((item) => (
        <div
          key={item.value}
          className={classNames(styles.item, 'z-check-tag-item', {
            [styles.actived]: isActived(item),
            'z-check-tag-item-actived': isActived(item),
          })}
          onClick={() => handleClick(item)}
        >
          {item.label}
          {Array.isArray(item.value) && (
            <div className={styles.arrow}>
              <i
                className={classNames(styles.icon, styles.up, {
                  [styles.actived]: iconIsActived(item, 0),
                })}
              />
              <i
                className={classNames(styles.icon, styles.down, {
                  [styles.actived]: iconIsActived(item, 1),
                })}
              />
            </div>
          )}
        </div>
      ))}
    </div>
  );
};

export default CheckTag;
